
#import <appkit/appkit.h>
#import <pwd.h>
#import "../Alexandra.h"
#import "FromHeaderController.h"
#import "FromHeaderPanel.h"
#import "askresolverfordomain.h" 

@implementation FromHeaderController

+ new
	{
	static FromHeaderController *me=nil;
	
	if(!me)
		me=[[FromHeaderController alloc] init];
	return me;
	}


- (char *)computeAddress;
	{
    char  machine_name[256], *domain_name;
    struct passwd *user;
    char  mail_address[512];
	const char *user_name;
	 
	user_name=NXUserName();
    user=getpwnam(user_name);
    gethostname(machine_name,sizeof(machine_name));
    domain_name=askresolverfordomain();
	 
	if(user_name) strcat(mail_address,user_name);
	strcat(mail_address,"@");
	if(machine_name){
	 	 strcat(mail_address,machine_name);
	 	 strcat(mail_address,".");
	 }
	if(domain_name) strcat(mail_address,domain_name);
	if(user){
		strcat(mail_address," (");
		strcat(mail_address,user->pw_gecos);
		strcat(mail_address,")");
	}
    return NXCopyStringBufferFromZone(mail_address,[self zone]);
	}


- (char *)validFromAddress;
	{
	KVPair		*pair;
	const char	*d;
	char		defname[200], defvalue[200],*fromAddress=NULL;
	int			i,n=[NXApp defaultIntValue:DEFAULT_XHEADER_COUNT],ret;
	BOOL		stopSearching=NO;

	for(i=0;i<n && !stopSearching;i++)
		{
		sprintf(defname,DEFAULT_XHEADERS,i+1);
		d=[NXApp defaultValue:defname];
		if(d)
			{
			pair=[[KVPair alloc] init:d delimiter:':'];
			if([pair isNull])
				stopSearching=YES;
			else if(!strcmp([pair key],"From"))
				{
				fromAddress=NXCopyStringBufferFromZone([pair value],[self zone]);
				stopSearching=YES;
				}				
			pair=[pair free];
			}
		}
	if(fromAddress)
		return fromAddress;

	if(!thePanel)
		[NXApp loadNibSection:"FromHeader.nib" owner:self];
	fromAddress=[self computeAddress];	
 	ret=[thePanel runModalForAddress:fromAddress];
	NXZoneFree([self zone],fromAddress);
	if(!ret)
		return NULL;
		
	fromAddress=(char *)[thePanel fromAddress];	
	if(i==n)
		[NXApp setDefault:DEFAULT_XHEADER_COUNT toInt:++i];
	sprintf(defvalue, "From: %s",fromAddress);
	sprintf(defname,DEFAULT_XHEADERS,i);
	[NXApp setDefault:defname to:defvalue];
	EM_ERROR(ENOTEPrefsChanged,self,NULL);

	return NXCopyStringBufferFromZone(fromAddress,[self zone]);
	}		
	

@end
